package grq

import (
	"go.uber.org/zap"
	"sync"
	"wzgames/internal/gloader"
	"wzgames/pkg/components/grabbitmq"
	"wzgames/pkg/logger"
)

var (
	_mgr *MqManager
	once sync.Once
)

type MqManager struct {
	mq     *grabbitmq.MQ
	inited bool

	producer1 *grabbitmq.Producer
}

func MqMgr() *MqManager {
	if _mgr == nil {
		once.Do(func() {
			_mgr = &MqManager{
				mq: gloader.CommMgr().MQ(),
			}
		})
	}

	return _mgr
}

func (q *MqManager) Init() error {
	var err error
	_, err = q.mq.Open()
	if err != nil {
		//logger.Error("err == ", zap.String("error", err.Error()))
		return err
	}

	logger.Info("[GRQ] rabbitmq mq manager start")
	q.inited = true

	return nil
}

func (q *MqManager) Destroy() {

}

func (q *MqManager) InitBetsProducer() error {
	producer1, err := q.mq.Producer(ProducerName1)
	if err != nil {
		//logger.Error("err == ", zap.String("error", err.Error()))
		return err
	}

	exb := []*grabbitmq.ExchangeBinds{
		{
			Exch: grabbitmq.DefaultExchange(DefaultExchange, grabbitmq.ExchangeTopic, nil),
		},
	}

	producer1.Confirm(true)
	if err = producer1.SetExchangeBinds(exb).Open(); err != nil {
		logger.Error("[GRQ] rabbitmq producer channel open fail", zap.String("Producer", ProducerName1), zap.Error(err))
		return err
	}

	q.producer1 = producer1
	logger.Info("[GRQ] rabbitmq bets producer start")
	return nil
}

func (q *MqManager) CreateConsumer(name string, exb []*grabbitmq.ExchangeBinds, msgChan chan grabbitmq.Delivery) (*grabbitmq.Consumer, error) {
	c, err := q.mq.Consumer(name)
	if err != nil {
		//logger.Error("err == ", zap.String("error", err.Error()))
		return nil, err
	}

	if err = c.SetExchangeBinds(exb).SetMsgCallback(msgChan).Open(); err != nil {
		logger.Error("[GRQ] rabbitmq consumer channel open fail", zap.String("Consumer", name), zap.Error(err))
		return nil, err
	}

	return c, nil
}

func (q *MqManager) PublishBets(exb, routeKey string, data []byte) bool {
	if q.producer1 == nil {
		return false
	}
	err := q.producer1.PublishP(exb, routeKey, data)
	if err != nil {
		logger.Error("[GRQ] rabbitmq producer publish message fail on PublishBets", zap.String("Producer", ProducerName1), zap.Error(err))
		return false
	}
	return true
}
